<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索和添加商品 -->
      <el-row :gutter="20" class="searchAddGoods">
        <!-- 实现搜索按钮按钮写在input里面 -->
        <el-col :span="9"
          ><el-input
            placeholder="请输入内容"
            v-model="queryGetListParams.query"
            clearable
            @clear="resetTable"
          >
            <!-- slot 是控制其放在input变单的位置 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchData"
            ></el-button></el-input
        ></el-col>
        <el-col :span="3">
          <el-button type="primary" @click="toAddGoods">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 商品列表区域 -->
      <el-table
        :data="goodsList"
        style="width: 100%"
        border
        stripe
        height="600"
      >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="goods_name" label="商品名称" width="850">
        </el-table-column>
        <el-table-column prop="goods_price" label="商品价格(元)">
        </el-table-column>
        <el-table-column prop="goods_weight" label="商品重量">
        </el-table-column>
        <el-table-column label="创建时间" width="200">
          <template slot-scope="scope">
            {{ scope.row.add_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editGoods(scope.row.goods_id)"
            ></el-button
            ><el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteGoods(scope.row.goods_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="goodsListSizeChange"
        @current-change="goodsListCurrentChange"
        :current-page="queryGetListParams.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="queryGetListParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 编辑商品的对话框 -->
    <el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="50%">
      <el-form
        ref="editform"
        :model="editGoodsFormValue"
        label-width="80px"
        :rules="editGoodsFormRules"
      >
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editGoodsFormValue.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model.number="editGoodsFormValue.goods_price"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_price">
          <el-input v-model.number="editGoodsFormValue.goods_weight"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_price">
          <el-input v-model.number="editGoodsFormValue.goods_number"></el-input>
        </el-form-item>
        <el-upload
          class="upload-demo"
          action="http://127.0.0.1:8888/api/private/v1/upload"
          :on-remove="handleRemove"
          :headers="uploadHeader"
          :on-success="uploadSuccess"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoodsSubmitBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取商品列表的请求参数
      queryGetListParams: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 商品列表
      goodsList: [],
      // total商品总数
      total: 0,
      // 控制编辑商品的对话框显示和隐藏
      editDialogVisible: false,
      // 编辑表单数据
      editGoodsFormValue: {},
      // 编辑表单验证规则
      editGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '不能为空' },
          { type: 'number', message: '必须为数字值' }
        ]
      },
      // 上传图片时带上请求头
      uploadHeader: {
        Authorization: sessionStorage.getItem('token')
      },
      // 完成编辑是发的请求体
      editGoodsBody: {
        pics: []
      }
    }
  },
  methods: {
    // 获取商品列表
    async getGoodsList() {
      // axios获取商品列表参数
      const res = await this.$http.get('goods', {
        params: this.queryGetListParams
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 自动换页
      if (
        res.data.goods.length === 0 &&
        this.queryGetListParams.pagenum !== 1
      ) {
        this.queryGetListParams.pagenum--
        return this.getGoodsList()
      }
      this.total = res.data.total
      this.goodsList = res.data.goods
    },
    // 页码条数改变触发
    goodsListSizeChange(val) {
      this.queryGetListParams.pagesize = val
      this.getGoodsList()
    },
    // 页码数改变
    goodsListCurrentChange(val) {
      this.queryGetListParams.pagenum = val
      this.getGoodsList()
    },
    // 实现收搜相应内容的功能
    // 可以实现优化但没必要
    searchData() {
      this.getGoodsList()
    },
    // 实现重置表格
    resetTable() {
      this.getGoodsList()
    },
    // 实现删除商品
    async deleteGoods(id) {
      const val = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (val !== 'confirm') {
        return this.$message('取消删除')
      }
      const res = await this.$http.delete('goods/' + id)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getGoodsList()
    },
    // 去到添加商品的组件
    toAddGoods() {
      this.$router.push('/goods/add')
    },
    // 编辑商品
    async editGoods(id) {
      // 更具id查询商品信息
      const res = await this.$http.get('goods/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editGoodsFormValue = res.data
      this.editDialogVisible = true
    },
    // 移除图片触发
    handleRemove(file) {
      const index = this.editGoodsBody.pics.findIndex(val => {
        return val.pic === file.response.data.tmp_path
      })
      this.editGoodsBody.pics.splice(index, 1)
    },
    // 上传成功监听函数
    uploadSuccess(res) {
      var pic = {
        pic: res.data.tmp_path
      }
      this.editGoodsBody.pics.push(pic)
    },
    // 完成编辑功能
    editGoodsSubmitBtn() {
      this.$refs.editform.validate(async valid => {
        if (!valid) {
          return this.$message.error('表单验证失败')
        }
        // 对提交的数据进行处理
        this.editGoodsBody.goods_name = this.editGoodsFormValue.goods_name
        this.editGoodsBody.goods_price = this.editGoodsFormValue.goods_price
        this.editGoodsBody.goods_weight = this.editGoodsFormValue.goods_weight
        this.editGoodsBody.goods_number = this.editGoodsFormValue.goods_number
        this.editGoodsBody.goods_cat = this.editGoodsFormValue.goods_cat
        // 发起axios请求
        const res = await this.$http.put(
          'goods/' + this.editGoodsFormValue.goods_id,
          this.editGoodsBody
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getGoodsList()
        this.editDialogVisible = false
      })
    }
  },
  mounted() {
    this.getGoodsList()
  }
}
</script>

<style lang="less" scoped>
.searchAddGoods {
  margin-bottom: 15px;
}
</style>
